/*
 * @Author: shawnxiao
 * @Date: 2021-04-11 11:42:38
 * @LastEditTime: 2021-10-15 10:43:42
 * @FilePath: /project/src/index/store/user/actionCreators.tsx
 */
import * as constants from './constants'
import { IAction } from '../types'
import {UserState} from './reducer'
// import {Dispatch} from 'redux'

import * as request from '@/index/apis/Login'
import { actionCreators } from '../app'
import { Modal } from 'antd'

export const setUserInfo = (user: UserState) => ({
  type: constants.SET_USER_INFO,
  payload: user
})

export const logout: () => IAction<null> = () => ({
  type: constants.SET_USER_LOGOUT,
  payload: null
})

export const getTokenFn = (flag: boolean) => (dispatch:any) => {
  return new Promise((resolve, reject) => {
      // 走apaas sso获取token
      request
        .checkLoginTokenFn({}).then((res:any) => {
          const status = !!(res.data.login && res.data.binding && res.data.tokenId)
          if (status) {
            dispatch(setUserInfo({token: res.data.tokenId} as any))
            resolve(status)
          } else {
            dispatch(logout())
            if (flag) {
              Modal.warning({
                title: '温馨提示',
                content: '您已登出，请重新登录!',
                okText: '确定',
                onOk: () => {
                  window.location.href = process.env.APP_LOGIN_URL as string
                }
              })
            }
          }
        })
        .catch((err) => {
          dispatch(logout())
          reject(err)
        })
  })
}
export const getUserInfoByToken:any = (token:string, flag:boolean, exchange: boolean) => (dispatch:any) => {
  return new Promise((resolve, reject) => {
    if (!exchange){
      request.getUserInfoByToken({token}).then((res:any) => {
        if (res?.data?.respData){
          const obj:any = {
            name: res.data.respData.name || '',
            realName: res.data.respData.name || '',
            uniScId: res.data.respData.departmentId || '',
            token,
            role: 'admin'
          }
          obj.requireBanding = false
          dispatch(setUserInfo({...obj, token}))
          resolve(res)
        } else {
          if (flag) {
            // 点击匹配按钮场景 登录失效
            Modal.warning({
              title: '温馨提示',
              content: '您已登出，请重新登录!',
              okText: '确定',
              onOk: () => {
                window.location.href = process.env.APP_LOGIN_URL as string
              }
            })
          }
        }
      }).catch((err) => {
        dispatch(setUserInfo({name: '', realName: '', token} as any))
        if (flag) {
          reject(err)
        }
      }).finally(() => {
        // 获取路由数组
        dispatch(actionCreators.getMenuList(true))
      })
    } else {
      // 不兑换用户信息
      dispatch(setUserInfo({name: '', realName: '', token} as any))
       // 获取路由数组
       dispatch(actionCreators.getMenuList(true))
    }
  })
}
